import Router from "koa-router";
import { pool } from "../../../config/database";
import { authMiddleware } from "../../../middleware/auth";
import { checkAdminPermission, successResponse, handleError } from "../common";
import { RowDataPacket, ResultSetHeader } from "mysql2";

const router = new Router({ prefix: "/api/admin/chat" });

// 获取聊天记录列表
router.get("/", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const {
      page = 1,
      limit = 20,
      user_id,
      room_id,
      message_type,
      is_read,
      keyword,
      start_date,
      end_date,
      sort = 'created_at_desc'
    } = ctx.query;

    // 参数验证和转换
    const pageNum = Math.max(1, parseInt(page as string) || 1);
    const limitNum = Math.min(Math.max(1, parseInt(limit as string) || 20), 100); // 最大100条，最小1条
    const offset = (pageNum - 1) * limitNum;

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    if (user_id) {
      whereConditions.push("cm.user_id = ?");
      queryParams.push(user_id);
    }

    if (room_id) {
      whereConditions.push("cm.room_id = ?");
      queryParams.push(room_id);
    }

    if (message_type) {
      whereConditions.push("cm.message_type = ?");
      queryParams.push(message_type);
    }

    if (is_read !== undefined) {
      whereConditions.push("cm.is_read = ?");
      queryParams.push(is_read === 'true' ? 1 : 0);
    }

    if (keyword) {
      whereConditions.push("cm.message LIKE ?");
      queryParams.push(`%${keyword}%`);
    }

    if (start_date) {
      whereConditions.push("cm.created_at >= ?");
      queryParams.push(start_date);
    }

    if (end_date) {
      whereConditions.push("cm.created_at <= ?");
      queryParams.push(end_date);
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';

    // 构建排序
    let orderClause = 'ORDER BY cm.created_at DESC';
    switch (sort) {
      case 'created_at_asc':
        orderClause = 'ORDER BY cm.created_at ASC';
        break;
      case 'created_at_desc':
        orderClause = 'ORDER BY cm.created_at DESC';
        break;
      case 'updated_at_asc':
        orderClause = 'ORDER BY cm.updated_at ASC';
        break;
      case 'updated_at_desc':
        orderClause = 'ORDER BY cm.updated_at DESC';
        break;
      case 'user_id_asc':
        orderClause = 'ORDER BY cm.user_id ASC, cm.created_at DESC';
        break;
      case 'room_id_asc':
        orderClause = 'ORDER BY cm.room_id ASC, cm.created_at DESC';
        break;
    }

    // 获取总数
    const countQuery = `
      SELECT COUNT(*) as total 
      FROM chat_messages cm 
      LEFT JOIN users u ON cm.user_id = u.id 
      ${whereClause}
    `;
    const [countResult] = await pool.execute(countQuery, queryParams) as [RowDataPacket[], any];
    const total = countResult[0].total;

    // 获取数据 - 使用字符串拼接方式避免参数问题
    const dataQuery = `
      SELECT 
        cm.id,
        cm.user_id,
        cm.message,
        cm.message_type,
        cm.room_id,
        cm.is_read,
        cm.created_at,
        cm.updated_at,
        u.username,
        u.email,
        u.nickname
      FROM chat_messages cm 
      LEFT JOIN users u ON cm.user_id = u.id 
      ${whereClause} 
      ${orderClause} 
      LIMIT ${limitNum} OFFSET ${offset}
    `;
    
    // 只传递WHERE条件的参数
    const [records] = await pool.execute(dataQuery, queryParams) as [RowDataPacket[], any];

         successResponse(ctx, {
       records,
       pagination: {
         page: pageNum,
         limit: limitNum,
         total,
         totalPages: Math.ceil(total / limitNum)
       }
     }, "获取聊天记录成功");

  } catch (error) {
    handleError(ctx, error, "获取聊天记录失败");
  }
});

// 获取聊天记录详情
router.get("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { id } = ctx.params;

    const [records] = await pool.execute(`
      SELECT 
        cm.id,
        cm.user_id,
        cm.message,
        cm.message_type,
        cm.room_id,
        cm.is_read,
        cm.created_at,
        cm.updated_at,
        u.username,
        u.email,
        u.nickname
      FROM chat_messages cm 
      LEFT JOIN users u ON cm.user_id = u.id 
      WHERE cm.id = ?
    `, [id]) as [RowDataPacket[], any];

    if (records.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: "聊天记录不存在"
      };
      return;
    }

    successResponse(ctx, records[0], "获取聊天记录详情成功");

  } catch (error) {
    handleError(ctx, error, "获取聊天记录详情失败");
  }
});

// 获取某个房间的所有聊天记录
router.get("/room/:room_id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { room_id } = ctx.params;
    const { sort = 'created_at_asc' } = ctx.query;

    let orderClause = 'ORDER BY cm.created_at ASC';
    if (sort === 'created_at_desc') {
      orderClause = 'ORDER BY cm.created_at DESC';
    }

    const [records] = await pool.execute(`
      SELECT 
        cm.id,
        cm.user_id,
        cm.message,
        cm.message_type,
        cm.room_id,
        cm.is_read,
        cm.created_at,
        cm.updated_at,
        u.username,
        u.email,
        u.nickname
      FROM chat_messages cm 
      LEFT JOIN users u ON cm.user_id = u.id 
      WHERE cm.room_id = ? 
      ${orderClause}
    `, [room_id]) as [RowDataPacket[], any];

    successResponse(ctx, records, "获取房间聊天记录成功");

  } catch (error) {
    handleError(ctx, error, "获取房间聊天记录失败");
  }
});

// 删除单条聊天记录
router.delete("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { id } = ctx.params;

    const [result] = await pool.execute(
      "DELETE FROM chat_messages WHERE id = ?",
      [id]
    ) as [ResultSetHeader, any];

    if (result.affectedRows === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: "聊天记录不存在"
      };
      return;
    }

    successResponse(ctx, null, "删除聊天记录成功");

  } catch (error) {
    handleError(ctx, error, "删除聊天记录失败");
  }
});

// 批量删除聊天记录
router.delete("/batch", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { ids } = ctx.request.body as { ids: number[] };

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "请提供要删除的记录ID数组"
      };
      return;
    }

    const placeholders = ids.map(() => '?').join(',');
    const [result] = await pool.execute(
      `DELETE FROM chat_messages WHERE id IN (${placeholders})`,
      ids
    ) as [ResultSetHeader, any];

    successResponse(ctx, {
      deletedCount: result.affectedRows
    }, `成功删除 ${result.affectedRows} 条聊天记录`);

  } catch (error) {
    handleError(ctx, error, "批量删除聊天记录失败");
  }
});

// 删除某个房间的所有聊天记录
router.delete("/room/:room_id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { room_id } = ctx.params;

    const [result] = await pool.execute(
      "DELETE FROM chat_messages WHERE room_id = ?",
      [room_id]
    ) as [ResultSetHeader, any];

    successResponse(ctx, {
      deletedCount: result.affectedRows
    }, `成功删除房间 ${room_id} 的 ${result.affectedRows} 条聊天记录`);

  } catch (error) {
    handleError(ctx, error, "删除房间聊天记录失败");
  }
});

// 删除某个用户的所有聊天记录
router.delete("/user/:user_id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { user_id } = ctx.params;

    const [result] = await pool.execute(
      "DELETE FROM chat_messages WHERE user_id = ?",
      [user_id]
    ) as [ResultSetHeader, any];

    successResponse(ctx, {
      deletedCount: result.affectedRows
    }, `成功删除用户 ${user_id} 的 ${result.affectedRows} 条聊天记录`);

  } catch (error) {
    handleError(ctx, error, "删除用户聊天记录失败");
  }
});

// 清理过期的聊天记录（可根据需要调整天数）
router.delete("/cleanup/expired", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { days = 30 } = ctx.query; // 默认清理30天前的记录

    const [result] = await pool.execute(
      "DELETE FROM chat_messages WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)",
      [days]
    ) as [ResultSetHeader, any];

    successResponse(ctx, {
      deletedCount: result.affectedRows,
      cleanupDays: Number(days)
    }, `成功清理 ${days} 天前的 ${result.affectedRows} 条聊天记录`);

  } catch (error) {
    handleError(ctx, error, "清理过期聊天记录失败");
  }
});

// 标记消息为已读/未读
router.put("/:id/read-status", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { id } = ctx.params;
    const { is_read } = ctx.request.body as { is_read: boolean };

    const [result] = await pool.execute(
      "UPDATE chat_messages SET is_read = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
      [is_read ? 1 : 0, id]
    ) as [ResultSetHeader, any];

    if (result.affectedRows === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: "聊天记录不存在"
      };
      return;
    }

    successResponse(ctx, null, `消息标记为${is_read ? '已读' : '未读'}成功`);

  } catch (error) {
    handleError(ctx, error, "更新消息状态失败");
  }
});

// 批量标记房间消息为已读
router.put("/room/:room_id/mark-read", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { room_id } = ctx.params;

    const [result] = await pool.execute(
      "UPDATE chat_messages SET is_read = 1, updated_at = CURRENT_TIMESTAMP WHERE room_id = ? AND is_read = 0",
      [room_id]
    ) as [ResultSetHeader, any];

    successResponse(ctx, {
      updatedCount: result.affectedRows
    }, `成功将房间 ${room_id} 的 ${result.affectedRows} 条未读消息标记为已读`);

  } catch (error) {
    handleError(ctx, error, "批量标记消息已读失败");
  }
});

// 获取聊天统计信息
router.get("/stats/overview", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    // 获取总记录数
    const [totalResult] = await pool.execute(
      "SELECT COUNT(*) as total FROM chat_messages"
    ) as [RowDataPacket[], any];

    // 获取今日记录数
    const [todayResult] = await pool.execute(
      "SELECT COUNT(*) as today FROM chat_messages WHERE DATE(created_at) = CURDATE()"
    ) as [RowDataPacket[], any];

    // 获取本周记录数
    const [weekResult] = await pool.execute(
      "SELECT COUNT(*) as week FROM chat_messages WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
    ) as [RowDataPacket[], any];

    // 获取未读消息数
    const [unreadResult] = await pool.execute(
      "SELECT COUNT(*) as unread FROM chat_messages WHERE is_read = 0"
    ) as [RowDataPacket[], any];

    // 获取活跃用户数
    const [activeUsersResult] = await pool.execute(
      "SELECT COUNT(DISTINCT user_id) as active_users FROM chat_messages WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
    ) as [RowDataPacket[], any];

    // 获取活跃房间数
    const [activeRoomsResult] = await pool.execute(
      "SELECT COUNT(DISTINCT room_id) as active_rooms FROM chat_messages WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
    ) as [RowDataPacket[], any];

    // 按消息类型统计
    const [typeStatsResult] = await pool.execute(
      "SELECT message_type, COUNT(*) as count FROM chat_messages GROUP BY message_type"
    ) as [RowDataPacket[], any];

    // 按房间统计消息数（前10个最活跃的房间）
    const [roomStatsResult] = await pool.execute(
      "SELECT room_id, COUNT(*) as message_count FROM chat_messages GROUP BY room_id ORDER BY message_count DESC LIMIT 10"
    ) as [RowDataPacket[], any];

    successResponse(ctx, {
      total: totalResult[0].total,
      today: todayResult[0].today,
      thisWeek: weekResult[0].week,
      unread: unreadResult[0].unread,
      activeUsers: activeUsersResult[0].active_users,
      activeRooms: activeRoomsResult[0].active_rooms,
      messageTypeStats: typeStatsResult,
      topActiveRooms: roomStatsResult
    }, "获取聊天统计信息成功");

  } catch (error) {
    handleError(ctx, error, "获取聊天统计信息失败");
  }
});

export default router;
